package com.starblink.utils.network.base

import com.apollographql.apollo3.api.ApolloRequest
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.http.DefaultHttpRequestComposer
import com.apollographql.apollo3.api.http.HttpRequest
import com.apollographql.apollo3.api.http.HttpRequestComposer

/**
 *  Create by yuanl at 2023/4/18
 **/
class SkApolloRequestComposer(url: String, private val enableSuffixPath: Boolean = true) :
    HttpRequestComposer {

    private val defaultComposer: DefaultHttpRequestComposer = DefaultHttpRequestComposer(url)

    override fun <D : Operation.Data> compose(apolloRequest: ApolloRequest<D>): HttpRequest {
        val httpReq = defaultComposer.compose(apolloRequest)

        if (enableSuffixPath) {
            return httpReq.newBuilder(httpReq.method, httpReq.url.let {
                val name = apolloRequest.operation.name()
                if (name.isNotEmpty()) {
                    "$it/$name"
                } else {
                    it
                }
            }).apply {
                if (httpReq.body != null) {
                    body(httpReq.body!!)
                }
            }.build()
        } else {
            return httpReq
        }
    }
}